import {getMenus} from '@/services/app'
import router from '@/router'

const state = {
  loading: false, // 加载状态
  menu: JSON.parse(localStorage.getItem('menu')) || [], // 主菜单
  menuActive: localStorage.getItem('menuActive') || '/', // 激活主菜单
  childMenu: JSON.parse(localStorage.getItem('childMenu')) || [], // 子菜单
  childMenuActive: localStorage.getItem('childMenuActive') || '/', // 激活子菜单
  initMenu: localStorage.getItem('initMenu') || '', // 获取初始子菜单 (key)
  initActive: '/' // 激活初始菜单
}

const getters = {
  getLoading: state => state.loading,
  getMenu: state => state.menu,
  getMenuActive: state => state.menuActive,
  getChildMenu: state => state.childMenu,
  getChildMenuActive: state => state.childMenuActive
}

const mutations = {
  // 更新加载状态
  LOADING: (state, data) => {
    state.loading = data
  },
  // 获取初始菜单
  MENU: (state, data) => {
    state.loading = false
    state.initMenu = state.initMenu || data[1].path
    state.menuActive = state.menuActive === state.initActive
      ? state.initMenu
      : state.menuActive // 获取初始子菜单 (key)
    const childMenu = data.filter(menu => menu.path === state.menuActive)[0].children
    state.menu = data // 获取主菜单
    state.childMenu = childMenu // 获取子菜单
    localStorage.setItem('menu', JSON.stringify(data))
    localStorage.setItem('initMenu', state.initMenu)
    localStorage.setItem('childMenu', JSON.stringify(childMenu))
  },
  // 获取子菜单
  MENU_SELECT: (state, data) => {
    if (data === state.initActive) {
      router.push(data) // 路由跳转
      state.menuActive = state.initActive // 激活主菜单
      state.childMenuActive = state.initActive // 激活子菜单
      localStorage.setItem('menuActive', state.initActive)
      localStorage.setItem('childMenuActive', state.initActive)
      return
    }
    const childMenu = state.menu.filter(menu => menu.path === data)[0].children
    state.initMenu = data // 变更获取初始子菜单 (key)
    state.childMenu = childMenu // 获取子菜单
    localStorage.setItem('initMenu', state.initMenu)
    localStorage.setItem('childMenu', JSON.stringify(childMenu))
  },
  // 激活菜单
  CHILD_MENU_SELECT: (state, data) => {
    const menuActive = `/${data.split('/')[1]}`
    router.push(data) // 路由跳转
    state.menuActive = menuActive // 激活主菜单
    state.childMenuActive = data // 激活子菜单
    localStorage.setItem('menuActive', menuActive)
    localStorage.setItem('childMenuActive', data)
  },
  // 重置菜单
  MENU_RESET: (state) => {
    state.menu = []
    state.childMenu = []
    state.menuActive = state.initActive
    state.childMenuActive = state.initActive
    localStorage.clear()
  }
}

const actions = {
  // 获取菜单
  handleMenu: ({commit}) => {
    getMenus().then(res => {
      commit('MENU', res.data)
      router.push('/') // 路由跳转首页
    })
  }
}

export default {state, getters, mutations, actions}
